<template>
  <a-layout class="w-full h-full">
    <Header />
    <a-layout-content>
      <a-layout class="h-full">
        <a-layout-sider class="h-full z-50">
          <a-menu
            v-model:selectedKeys="selectedKeys"
            mode="inline"
            class="menu-top"
            :items="menus"
            :open-keys="openKeys"
            @select="onMenuClick"
            @open-change="onOpenChange"
          />
        </a-layout-sider>
        <a-layout-content class="m-2"> <router-view /> </a-layout-content>
      </a-layout>
    </a-layout-content>
  </a-layout>
</template>
<script setup>
import { nextTick, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import useMenu from '@/hooks/useMenu'
import Header from './Header.vue'

const router = useRouter()
const selectedKeys = ref([])
const openKeys = ref([])
const { menus, menuSubKeys } = useMenu()
//页面刷新时菜单自动选中当前路由
watchEffect(() => {
  const activeMenu = router.currentRoute.value.meta.activeMenu //指定高亮菜单
  const path = router.currentRoute.value.path
  if (path === '/report') {
    const fullPath = router.currentRoute.value.fullPath
    const query = router.currentRoute.value.query
    selectedKeys.value = [fullPath]
    nextTick(() => {
      openKeys.value = [`${path}?categoryId=${query['categoryId']}`]
    })
  } else {
    openKeys.value = [path.substring(0, path.lastIndexOf('/'))]
    selectedKeys.value = [activeMenu || path]
  }
})

const onMenuClick = ({ key }) => {
  router.push(key)
}

//同一时间只能展开一个菜单
const onOpenChange = (keys) => {
  const latestOpenKey = keys.find((key) => openKeys.value.indexOf(key) === -1)
  if (menuSubKeys.value.indexOf(latestOpenKey) === -1) {
    openKeys.value = keys
  } else {
    openKeys.value = latestOpenKey ? [latestOpenKey] : []
  }
}
</script>
<style lang="less" scoped>
:deep(.ant-menu) {
  border-inline-end: none !important;
  .ant-menu-item-group-title {
    display: none;
  }
  .ant-menu-item-selected {
    // color: #fff;
    // background-color: var(--primary-color) !important;
  }
}
.menu-top {
  height: 100%;
  padding-bottom: 100px;
  overflow: auto;
}
</style>
